package com.hourses.service.impl;

import com.alibaba.fastjson2.JSON;
import com.hourses.mapper.AuthMapper;
import com.hourses.pojo.Auth;
import com.hourses.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author:LiTao
 * @Date:2025/4/27 15:35
 */
@Service
public class AuthServiceImpl implements AuthService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AuthMapper authMapper;
    @Override
    public List<Auth> getAuthTree(Integer userId) {
        //根据userId从缓存当中去找有没有缓存过权限树
        //缓存格式：  key ： authTree:"userId"
        String authTree = redisTemplate.opsForValue().get("authTree:" + userId);
        if (StringUtils.hasText(authTree)){
            //如果有缓存，将缓存内容从json格式转换为List格式返回
            List<Auth> resAuthTree = JSON.parseArray(authTree, Auth.class);
            return resAuthTree;
        }
        //没有缓存的情况
        //先把当前用户的所有权限查询出来
        List<Auth> allAuths = authMapper.selectAuthByUserId(userId);
        //再把查询到的权限转换为权限树
        List<Auth> changedTree = allAuthToAuthTree(allAuths, 0);
        //再将权限树转换为json字符串存入缓存中去
        redisTemplate.opsForValue().set("authTree:"+userId, JSON.toJSONString(changedTree));
        //最后返回菜单树
        return changedTree;
    }


    //获取所有的Auth
    @Override
    public List<Auth> getAllAuthTree() {
        //先查缓存
        String allAuths = redisTemplate.opsForValue().get("allAuths:");
        if (StringUtils.hasText(allAuths)){
            //有缓存的情况
            return JSON.parseArray(allAuths,Auth.class);
        }
        //没有缓存
        //先把数据库中auth_info表中可以用的权限查出来
        List<Auth> auths = authMapper.selectAllAuths();
        //转换为权限树
        List<Auth> authsTree = allAuthToAuthTree(auths, 0);
        //再存储到缓存当中去
        redisTemplate.opsForValue().set("allAuths:",JSON.toJSONString(authsTree));
        //最后返回菜单树
        return authsTree;
    }

    //将所有权限转换为权限树的算法
    public List<Auth> allAuthToAuthTree(List<Auth> allAuths, Integer pid){
        List<Auth> firstLevelAuths = new ArrayList<>();
        for (Auth auth:allAuths){
            if (auth.getParentId()==pid){
                firstLevelAuths.add(auth);
            }
        }

        for (Auth auth:firstLevelAuths){
            List<Auth> chiledAuth = allAuthToAuthTree(allAuths,auth.getAuthId());
            auth.setChildAuth(chiledAuth);
        }
        return firstLevelAuths;
    }
}
